<template>
  <Dialog v-model="dialogVisible" title="添加至文件管理" width="500" align-center>
    <el-form @submit.prevent label-width="140px" :model="formData" ref="formRef" :rules="rules">
      <el-form-item label="上级节点" prop="pid">
        <el-tree-select
          style="width: 400px"
          ref="treeGroupRef"
          v-model="formData.pid"
          value-key="id"
          node-key="id"
          :data="treeGroupData"
          :props="{ label: 'name' }"
          :render-after-expand="false"
          placeholder="请选择上级节点"
          check-strictly
          :default-expanded-keys="['0']"
        />
      </el-form-item>
      <el-form-item label="文件组名称" prop="groupName" class="col-item">
        <ns-input style="width: 100%" v-model="formData.groupName" placeholder="请输入文件组名称" />
      </el-form-item>
      <template v-if="formData.groupName">
        <el-form-item label="归属机构:" prop="deptId">
          <el-cascader
            ref="deptCascader"
            v-model="formData.deptId"
            placeholder="请选择归属机构"
            style="width: 100%"
            :props="cascaderProps"
            :options="deptList"
            filterable
            clearable
            value-on-clear=""
            :filter-method="sysFilterMethod"
          />
        </el-form-item>
        <el-form-item label="归属系统:" prop="sysId">
          <el-cascader
            ref="systemCascader"
            v-model="formData.sysId"
            placeholder="请选择归属系统"
            :props="systemCascaderProps"
            :options="systemList"
            style="width: 100%"
            filterable
            clearable
            value-on-clear=""
            :filter-method="sysFilterMethod"
          />
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submit" :disabled="formLoading">确定</el-button>
      <el-button @click="closeDialog">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { useGroupTree } from '@/hooks/web/useFileTree'
import type { FormInstance } from 'element-plus'
import { handleTree } from '@/utils/tree'
import { getSimpleDeptList } from '@/api/system/dept'
import { sysFilterMethod } from '@/utils/selectFilter'
import { getSimpleSystemList } from '@/api/asset/taskManage'
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false)

const formRef = ref<FormInstance>()
const deptList = ref([])
const systemList = ref([])
const data = reactive({
  formData: {
    pid: '0',
    groupName: '',
    sysId: '',
    deptId: ''
    // groupId: ''
  },

  fileGroupType: 1,
  childGroup: []
})

const isRequired = computed(() => {
  return !formData.value.deptId && !formData.value.sysId
})
const rules = computed(() => ({
  pid: [{ required: true, message: '请选择上级节点', rigger: ['blur', 'change'] }],
  groupName: [{ required: false, message: '请输入文件组名称', rigger: ['blur', 'change'] }],
  groupId: [{ required: true, message: '请选择目标文件组', rigger: ['blur', 'change'] }],
  deptId: [{ required: isRequired.value, message: '归属机构不能为空', trigger: 'change' }],
  sysId: [{ required: isRequired.value, message: '归属系统不能为空', trigger: 'change' }]
}))

const { treeGroupData, reFreshTreeData } = useGroupTree()

const { formData } = toRefs(data)

/** 打开弹窗 */
const open = async () => {
  getDeptList()
  getSystemList()
  dialogVisible.value = true
  reFreshTreeData()
}

async function getDeptList() {
  const data = await getSimpleDeptList()
  deptList.value = data
}
async function getSystemList() {
  const data = await getSimpleSystemList()
  systemList.value = handleTree(data, 'id', 'pid')
}

async function submit() {
  await formRef.value?.validate()
  const data = toRaw(formData.value)
  emit('success', data)
  //
  // if (formType.value === 'create') {
  //   await createKeyword(data)
  //   message.success(t('common.createSuccess'))
  // } else {
  //   await updateKeyword(data)
  //   message.success(t('common.updateSuccess'))
  // }
  // closeDialog()
  // // 发送操作成功的事件
}

defineExpose({ open, close: closeDialog, setBtnStatus }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

function closeDialog() {
  dialogVisible.value = false
}

function setBtnStatus(status: boolean) {
  formLoading.value = status
}

/** 重置表单 */
const resetForm = () => {
  formRef.value?.resetFields()
}

const systemCascaderProps = reactive({
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
})
const cascaderProps = reactive({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false // 用于 cascader 组件：在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
})

watch(dialogVisible, (show) => {
  !show && resetForm()
})
</script>
<style lang="scss" scoped></style>
